import 'dart:io';

import 'package:mp3_info/mp3_info.dart';

var artworks = <Artwork>[];

class Artwork {
  String path = "";
  String id = "";
  String cover = "";
  String title = "";
  int price = 0;
  int dl_count = 0; // 销量
  String maker_id = "";
  int age_category = 1;
  double rate_average_2dp = 0.0;

  List<Track> tracks = <Track>[];

  Artwork(this.id, this.path);

  Duration getDuration() {
    var duration = Duration();
    for (final track in tracks) {
      duration =
          Duration(seconds: duration.inSeconds + track.duration.inSeconds);
    }
    return duration;
  }
}

class Track {
  String name = "";
  String path = "";

  Duration duration;

  Track(this.name, this.path, this.duration);

  @override
  String toString() {
    // TODO: implement toString
    return name;
  }
}

// class Manager {

String get_rj(String name) {
  // 正则表达式，忽略大小写并匹配以rj开头的字符串，后面跟着一组数字
  RegExp regExp = RegExp(r'RJ\d+', multiLine: false);

  // 遍历字符串列表并尝试匹配

  RegExpMatch? match = regExp.firstMatch(name);
  if (match != null) {
    // 提取数字部分
    String numbers = match.group(0)!.substring(2); // 忽略前两个字符'rj'
    return numbers;
  }
  return name;
}

String get_tarck(String path) {
  var name = path.split("\\").last.split(".");
  return name.length == 2 ? name.first : name[name.length - 2];
}

void scan(Directory directory) {
  artworks.clear();
  final files = directory.listSync();
  for (final fileOrDir in files) {
    if (fileOrDir is Directory) {
      print(fileOrDir.path);
      var work = Artwork(get_rj(fileOrDir.path), fileOrDir.path);
      scan_track(fileOrDir, work);
      artworks.add(work);
    }
  }
}

void scan_track(Directory dir, Artwork artwork) {
  print("scan_track ${artwork.id} ${dir.path}");
  final files = dir.listSync();
  for (final file in files) {
    if (file is Directory) {
      scan_track(file, artwork); // 递归遍历子目录
    } else if (file is File) {
      if (file.path.endsWith(".mp3")) {
        artwork.tracks.add(Track(get_tarck(file.path), file.path,
            MP3Processor.fromFile(file).duration));
        print("${artwork.id}+1 ${file.path}");
      } else if (file.path.endsWith(".jpg")) {
        artwork.cover = file.path;
        print("${artwork.id}+cover ${file.path}");
      }
    }
  }
}
// }
